package dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import util.JDBCUtils;
import bean.User;

public class UserDao {
	public User getUser(int id) {
		Connection conn = JDBCUtils.getConnection();
		User user = new User();
		Statement stmt = null;
		ResultSet rs = null;
		try {
			stmt = conn.createStatement();
			String sql = "select * from users where id = " + id;
			rs = stmt.executeQuery(sql);
			while(rs.next()) {
				user.setName(rs.getString("name"));
				user.setEmail(rs.getString("email"));
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				rs.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			rs = null;
			try {
				stmt.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			stmt = null;
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			conn = null;
		}
		return user;
	}

	public Boolean insert(User user) {
		// TODO Auto-generated method stub
		Connection conn = JDBCUtils.getConnection();
		Statement stmt = null;
		boolean bool = false;
		try {
			stmt = conn.createStatement();
			String sql = "insert into users (name, password, email) values ( '" + user.getName() + "','"
					+ user.getPassword() + "','" + user.getEmail() + "')";
			int rs = stmt.executeUpdate(sql); 
			
			if (rs > 0) {
				bool = true;
			} else {
				bool = false;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				stmt.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			stmt = null;
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			conn = null;
		}
		return bool;
	}
}
